const Status = require('../models/Status');
const Type = require('../models/Type');
const Department = require('../models/Department');
const JobTicket = require('../models/JobTicket');
const dayjs = require('dayjs');
const StatusNames = [
    '待处理', '处理中', '已处理', '已关闭'
];
const TypeNames = [
    '施工作业', '动火作业', '高处作业', '有限空间'
];
const DepartmentNames = [
    '设施工程部', '安全环保部', '党委工作部', '技术装备中心', '复合材料中心'
];
// 工作地点列表
const WorkPlaces = [
    '生产车间A', '生产车间B', '仓库区', '办公区', '研发中心',
    '维修车间', '质检区', '包装车间', '配电房', '锅炉房'
];

// 工作内容模板
const WorkContentTemplates = [
    '设备维护与保养', '生产线故障排查', '安全隐患整改', '设备升级改造',
    '环境卫生清理', '消防设施检查', '电力系统维护', '管道检修',
    '空调系统维护', '网络设备升级'
];

// 工作公司列表
const WorkCompanies = [
    '诚信设备维修有限公司', '安全技术服务公司', '机电安装工程公司',
    '环保科技有限公司', '自动化系统集成商', '消防工程公司',
    '电力设备维修公司', '管道工程有限公司', '空调维修服务中心',
    '网络科技有限公司'
];
const mockStatus = async () => {
    return new Promise(async (resolve, reject) => {
        try {
            const generateStatus = async (count = 4) => {
                const statusList = [];
                for (let i = 0; i < count; i++) {
                    const status = new Status({
                        name: StatusNames[i]
                    });
                    statusList.push(status);
                }
                await Status.insertMany(statusList);
                console.log(`成功生成 ${count} 条状态数据`);
                return statusList;
            }
            let res = await generateStatus();
            console.log(res, '状态初始化')
            resolve(res);
        } catch (error) {
            console.log(error, '状态初始化失败')
            reject(error);
        }

    }).catch((err) => {
        console.log(err, '状态初始化失败')

    })
}

const mockType = async () => {
    return new Promise(async (resolve, reject) => {
        try {
            const generateType = async (count = 4) => {
                const typeList = [];
                for (let i = 0; i < count; i++) {
                    const type = new Type({
                        name: TypeNames[i]
                    });
                    typeList.push(type);
                }
                await Type.insertMany(typeList);
                console.log(`成功生成 ${count} 条类型数据`);
                return typeList;
            }
            let res = await generateType();
            console.log(res, '类型初始化')
            resolve(res);
        } catch (error) {
            console.log(error, '类型初始化失败')
            reject(error);
        }

    }).catch((err) => {
        console.log(err, '类型初始化失败')

    })
}
const mockDepartment = async () => {
    return new Promise(async (resolve, reject) => {
        try {
            const generateDepartment = async (count = 5) => {
                const departmentList = [];
                for (let i = 0; i < count; i++) {
                    const department = new Department({
                        name: DepartmentNames[i]
                    });
                    departmentList.push(department);
                }
                await Department.insertMany(departmentList);
                console.log(`成功生成 ${count} 条部门数据`);
                return departmentList;
            }
            let res = await generateDepartment();
            console.log(res, '部门初始化')
            resolve(res);
        } catch (error) {
            console.log(error, '部门初始化失败')
            reject(error);
        }

    }).catch((err) => {
        console.log(err, '部门初始化失败')

    })
}



// 生成500条工单数据的函数
const mockJobTicket = async (count = 500) => {
    return new Promise(async (resolve, reject) => {
        try {
            // 获取已有的部门和类型数据
            const departments = await Department.find();
            const types = await Type.find();
            const statuses = await Status.find();

            if (departments.length === 0 || types.length === 0) {
                console.log('部门或类型数据为空，无法生成工单数据');
                resolve([]);
                return;
            }

            const generateJobTickets = async () => {
                const jobTickets = [];

                for (let i = 0; i < count; i++) {
                    // 随机选择部门和类型
                    const department = departments[Math.floor(Math.random() * departments.length)];
                    const type = types[Math.floor(Math.random() * types.length)];
                    const status = statuses[Math.floor(Math.random() * statuses.length)];

                    // 随机生成工作时间（过去30天内）
                    const baseTime = Date.now() - Math.floor(Math.random() * 30) * 24 * 60 * 60 * 1000;
                    const workStartTime = baseTime - Math.floor(Math.random() * 7) * 24 * 60 * 60 * 1000;
                    const workEndTime = workStartTime + Math.floor(Math.random() * 168) * 60 * 60 * 1000; // 最多7天

                    // 随机选择工作地点、内容和公司
                    const workPlace = WorkPlaces[Math.floor(Math.random() * WorkPlaces.length)];
                    const workContentTemplate = WorkContentTemplates[Math.floor(Math.random() * WorkContentTemplates.length)];
                    const workContent = `${workContentTemplate}`;
                    const workCompany = WorkCompanies[Math.floor(Math.random() * WorkCompanies.length)];

                    // 随机生成状态
                    // const status = Math.floor(Math.random() * 4);

                    const jobTicket = new JobTicket({
                        departmentId: department._id,
                        typeId: type._id,
                        createTime: baseTime,
                        workPlace: workPlace,
                        workContent: workContent,
                        workCompany: workCompany,
                        workStartTime: workStartTime,
                        workEndTime: workEndTime,
                        statusId: status._id
                    });

                    jobTickets.push(jobTicket);
                }

                // 批量插入数据库
                await JobTicket.insertMany(jobTickets);
                console.log(`成功生成 ${count} 条工单数据`);
                return jobTickets;
            };

            let res = await generateJobTickets();
            console.log(res.slice(0, 2), '工单初始化（只显示前两条）');
            resolve(res);
        } catch (error) {
            console.log(error, '工单生成失败');
            reject(error);
        }
    }).catch((err) => {
        console.log(err, '工单初始化失败');
    });
};


const initBaseData = async () => {
    await mockStatus();
    await mockType();
    await mockDepartment();
    await mockJobTicket(100000)
    //根据以上信息随机生成100条工单数据

}

module.exports = {
    initBaseData
}
